package com.feihao.zhou.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebFilter("/stu/*")
public class LoginFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        /*HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        Object username = request.getSession().getAttribute("username");

        if (username==null){
            //拦截
            response.sendRedirect("/login.jsp");
        }else {
            filterChain.doFilter(request,response);
        }*/

        //获取是否有登录信息：
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        Object username = request.getSession().getAttribute("username");
        if (username == null || "".equals(username)) {
            //没有信息，重定向到登录界面：
            response.sendRedirect(request.getContextPath() + "/login.jsp");
            return;
        } else {
            //如果有信息：放行：
            filterChain.doFilter(request, response);
        }
    }

    @Override
    public void destroy() {

    }
}
